package Homework3

import java.io.{BufferedWriter, FileWriter}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.Source

object ProcessData {
  def main(args: Array[String]): Unit = {
    val file = Source.fromFile("src/main/scala/Homework3/data.txt", "UTF8")
    // 记录{用户：{地点：[（时间，停留时长）]}}
    val userLocationTime = new mutable.HashMap[String, mutable.HashMap[String, ListBuffer[(Int, Int)]]]
    val lines = file.getLines()
    for (line <- lines) {
      val items = line.split(",")
      // 获取某用户的{地点：[（时间，停留时长）]}数据
        userLocationTime.get(items(0)) match {
        case None =>
          // 若为空则添加用户以及地点列表
          val locationTime = mutable.HashMap(items(1) -> ListBuffer((items(2).toInt, items(3).toInt)))
          userLocationTime(items(0)) = locationTime
        case Some(locationTime) =>
          // 获取某用户某地点的[（时间，停留时长）]
          locationTime.get(items(1)) match {
            case None =>
              val timeList = (items(2).toInt, items(3).toInt)
              locationTime(items(1)) = ListBuffer(timeList)
              userLocationTime(items(0)) = locationTime
            case Some(timeList) =>
              timeList.append((items(2).toInt, items(3).toInt))
              // 按时间进行排序
              val newTimeList = timeList.sortBy(t => t._1)
              // 对停留时间进行求和，存储在列表第一个元组的停留时长上
              var time = 0
              newTimeList.foreach(t => time += t._2)
              newTimeList(0) = (newTimeList.head._1, time)
              locationTime(items(1)) = newTimeList
              userLocationTime(items(0)) = locationTime
          }
      }
    }
    file.close()

    // 将合并后的数据写入文件
    val writer = new BufferedWriter(new FileWriter("src/main/scala/Homework3/output.txt"))
    for (ult <- userLocationTime){
      for (lt <- ult._2){
        writer.write(ult._1 + "," +lt._1 + "," + lt._2.head._1 + "," + lt._2.head._2 + "\n")
      }
    }
    writer.flush()
    writer.close()

  }
}
